package TruongNhaLib;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import Config.setting;
import android.content.Context;
import android.util.Log;

public class UserFunctions {
	static String csrfmiddlewaretoken = "";
	private JSONParser jsonParser;
	private static String host = setting.getHost();
	private static String loginURL = host + "api/login/";
	private static String postStudentListURL = host + "api/attendance/";
	private static String sumitmarkURL = host + "api/submitmark/";
	private static String registerURL = host + "api/resigter";
	private static String register_tag = "register";

	// constructor
	public UserFunctions() {
		jsonParser = new JSONParser();
	}

	public boolean isSavedSession(Context context) {
		return jsonParser.isSavedSession(context);
	}

	/**
	 * function make Login Request
	 * 
	 * @param username
	 * @param password
	 * */
	public JSONObject loginUser(Context context, String username,
			String password) {
		// Building Parameters

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password));
		Log.e("JSON", "In login user 02");
		Log.e("JSON", "Start Get csrf");
		csrfmiddlewaretoken = new JSONParser().getCsrfFromUrl(loginURL);
		Log.e("JSON", "End csrf");
		params.add(new BasicNameValuePair("csrfmiddlewaretoken",
				csrfmiddlewaretoken));
		Log.e("JSON", "Start POST");
		JSONObject json = jsonParser.getJSONFromUrl(context, loginURL, params);
		Log.e("JSON", "END POST");
		Log.e("JSON", json.toString());
		return json;
	}

	/**
	 * function make Login Request
	 * 
	 * @param context
	 * @param remember
	 * */
	public JSONObject loginUser(Context context) {
		DatabaseHandler db = new DatabaseHandler(context);
		String[] remember = db.getRemember();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		Log.e("remember[0]= ", remember[0] + "");
		Log.e("remember[1]= ", remember[1] + "");
		params.add(new BasicNameValuePair("username", remember[0]));
		params.add(new BasicNameValuePair("password", remember[1]));
		Log.e("JSON", "In login user 02");
		Log.e("JSON", "Start Get csrf");
		csrfmiddlewaretoken = new JSONParser().getCsrfFromUrl(loginURL);
		Log.e("JSON", "End csrf");
		params.add(new BasicNameValuePair("csrfmiddlewaretoken",
				csrfmiddlewaretoken));
		Log.e("JSON", "Start POST");
		JSONObject json = jsonParser.getJSONFromUrl(context, loginURL, params);
		Log.e("JSON", "END POST");
		/*
		 * JSONObject json = jsonParser.TestgetJSONFromUrl(loginURL, params);
		 * Log.e("JSON", "In login user 03");
		 */Log.e("JSON", json.toString());
		return json;
	}

	/**
	 * Store remember username & password
	 * 
	 * @param username
	 * @param password
	 * */
	public void addRemember(Context context, String username, String password,
			String type) {
		DatabaseHandler db = new DatabaseHandler(context);
		db.addRemember(username, password, type);
	}

	public int postStudentList(List<Model> list, String date, String classId) {
		// Building Parameters
		StringBuilder attend = new StringBuilder();
		boolean send = false;
		int size = list.size();
		int status;
		int i, k = 0;
		for (i = 0; i < size; i++) {
			status = list.get(i).getStatus();
			switch (status) {
			case 0: {
				send = true;
				attend.append(list.get(i).getId()).append("-");
				attend.append("K");
				attend.append("-").append(date);
				k = i;
				i = size;
				break;
			}
			case 1: {
				send = true;
				attend.append(list.get(i).getId()).append("-");
				attend.append("P");
				attend.append("-").append(date);
				k = i;
				i = size;
				break;
			}
			case 2: {
				send = true;
				attend.append(list.get(i).getId()).append("-");
				attend.append("M");
				attend.append("-").append(date);
				k = i;
				i = size;
				break;
			}
			default:
				break;
			}
		}// end for.
		for (int j = k; j < size; j++) {
			status = list.get(j).getStatus();
			switch (status) {
			case 0: {
				attend.append("%").append(list.get(j).getId()).append("-");
				attend.append("K");
				attend.append("-").append(date);
				break;
			}
			case 1: {
				attend.append("%").append(list.get(j).getId()).append("-");
				attend.append("P");
				attend.append("-").append(date);
				break;
			}
			case 2: {
				attend.append("%").append(list.get(j).getId()).append("-");
				attend.append("M");
				attend.append("-").append(date);
				break;
			}
			default:
				break;
			}
		}// end for.
		int statusCode = -1;
		if (send) {
			Log.d("LIST", attend.toString());
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("date", date));
			params.add(new BasicNameValuePair("classId", classId));
			params.add(new BasicNameValuePair("list", attend.toString()));
			params.add(new BasicNameValuePair("csrfmiddlewaretoken",
					csrfmiddlewaretoken));
			Log.e("JSON 1", postStudentListURL);
			statusCode = jsonParser.postSubmit(postStudentListURL, params);
			// statusCode = jsonParser.postStudentList(postStudentListURL,
			// params);
			Log.e("JSON 2", postStudentListURL);
		}
		/*
		 * JSONObject json = jsonParser.TestgetJSONFromUrl(loginURL, params);
		 * Log.e("JSON", "In login user 03");
		 */return statusCode;
	}

	// submmit one mark
	public int submitMark(String url, String data) {
		// Building Parameters
		int statusCode = -1;// It mean nothing to change.
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("data", data));
		params.add(new BasicNameValuePair("csrfmiddlewaretoken",
				csrfmiddlewaretoken));
		Log.e("JSON 1", url);
		statusCode = jsonParser.postSubmit(url, params);
		Log.e("JSON 2", url);
		return statusCode;
	}

	// submit all mark
	public int submitMark(List<MarkModel> list, String classId, String url) {
		// Building Parameters
		StringBuilder marks = new StringBuilder();
		int size = list.size();
		Log.d("size submit = ", size + "");
		int statusCode = -1;// It mean nothing to change.
		if (size > 0) {// De phong truong hop lop ko co hoc sinh nao thi k phai
						// post
			MarkModel aDiem;
			marks.append("[");
			for (int i = 0; i < size - 1; i++) {
				aDiem = list.get(i);
				marks.append(aDiem.getDiemStringToSubmit()).append(",");
			}// end for.
			marks.append(list.get(size - 1).getDiemStringToSubmit())
					.append("]");
			Log.d("LIST submit mark final ", marks.toString());
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("classId", classId));
			params.add(new BasicNameValuePair("data", marks.toString()));
			params.add(new BasicNameValuePair("csrfmiddlewaretoken",
					csrfmiddlewaretoken));
			Log.e("JSON 1", url);
			Log.d("Marks result: ", marks.toString());
			statusCode = jsonParser.postSubmit(url, params);
			Log.e("JSON 2", url);
		}
		/*
		 * JSONObject json = jsonParser.TestgetJSONFromUrl(loginURL, params);
		 * Log.e("JSON", "In login user 03");
		 */return statusCode;
	}

	public int submitMark(MarkModel obj, String url) {
		// Building Parameters
		int statusCode = -1;// It mean nothing to change.
		String mark = obj.getDiemStringToSubmit();
		Log.d("LIST submit mark final ", mark);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("data", mark));
		params.add(new BasicNameValuePair("csrfmiddlewaretoken",
				csrfmiddlewaretoken));
		Log.e("JSON 1", url);
		statusCode = jsonParser.postSubmit(url, params);
		return statusCode;
	}

	/**
	 * Function return the user type
	 * */
	public static String userType(Context context) {
		DatabaseHandler db = new DatabaseHandler(context);
		return db.userType();
	}

	/**
	 * Function get Login status
	 * */
	public boolean isUserLoggedIn(Context context) {
		DatabaseHandler db = new DatabaseHandler(context);
		int count = db.getRowCount("login");
		if (count > 0) {
			// user logged in
			return true;
		}
		return false;
	}

	/**
	 * Function get isRemember
	 * */
	public boolean isRemember(Context context) {
		DatabaseHandler db = new DatabaseHandler(context);
		int count = db.getRowCount("remember");
		Log.d("isRemember", "count: " + count);
		if (count > 0) {
			// is remembered before:
			return true;
		}
		return false;
	}

	public boolean isRememberStudent(Context context) {
		DatabaseHandler db = new DatabaseHandler(context);
		String[] rem = db.getRemember();
		if (rem[2].equals("1"))
			return true;
		return false;
	}

	/**
	 * Function to logout user Reset all Database
	 * */
	public boolean logoutUser(Context context) {
		DatabaseHandler db = new DatabaseHandler(context);
		db.resetTables();
		jsonParser.clearSession(context);
		Log.e("LOGGED OUT", " Logged out");
		return true;
	}

	/**
	 * Function to delData user Reset all Database except rememberTable
	 * */
	public boolean delData(Context context) {
		DatabaseHandler db = new DatabaseHandler(context);
		db.delData();
		Log.e("DELETED data", " Del data");
		return true;
	}

}